package com.vpx.server.framework.interceptor;

import com.alibaba.fastjson.JSON;
import com.vpx.server.framework.aop.ServiceSectionHandler;
import com.vpx.server.framework.authority.*;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.base.SessionContext;
import com.vpx.server.framework.config.SystemConfig;
import com.vpx.server.framework.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author lihui
 * @title: vpx
 * @module system
 * @description: 权限拦截去
 * @date 2021/9/12 11:45
 */
@Component
public class AuthorityInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(ServiceSectionHandler.class);

    @Autowired
    SystemConfig systemConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("text/html; charset=UTF-8");
        String uri = request.getRequestURI();
        logger.info("request uri:" + uri);
        return true;

//        String sid = request.getHeader("sid");
//        if (StringUtils.isEmpty(sid)) {
//            sid = request.getParameter("sid");
//        }
//        if (StringUtils.isEmpty(sid)) {
//            writeErrorMsg(response, ResultMsg.SID_NULL_CODE, "sid is required!");
//            return false;
//        }
//
//        String key = SessionContext.getSessionRedisKey(sid);
//        SessionInfo sessionInfo = SessionStoreManager.getSession(key);
//
//        if (sessionInfo == null) {
//            writeErrorMsg(response, ResultMsg.SID_EXPIRE, "sid not found!");
//            return false;
//        }
//
//        SessionUtil.init(sessionInfo);
//
//        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        Method method = handlerMethod.getMethod();
//
//        RequestAuth annotation = method.getAnnotation(RequestAuth.class);
//        //如果controller未设置访问策略的，默认为登录可访问
//        AuthPoicy authPoicy = null;
//        String[] allows = null;
//        if (annotation != null) {
//            authPoicy = annotation.poicy();
//            allows = annotation.allows();
//        } else {
//            authPoicy = AuthPoicy.LOGIN;
//            allows = new String[]{};
//        }
//
//        SessionUser sessionUser = sessionInfo.getSessionUser();
//        switch (authPoicy) {
//            case UNLOGIN: {
//
//                return true;
//            }
//            case LOGIN: {
//                if (sessionUser == null) {
//                    writeUnloginMsg(response);
//                    return false;
//                }
//                return true;
//            }
//            case AUTH: {
//                if (sessionUser == null) {
//                    writeUnloginMsg(response);
//                    return false;
//                }
//
//
//                if (true) {
//                	//接入权限之前，屏蔽授权检查
//                    return true;
//                }
//
//                if (!authCheck(sessionUser, uri, allows)) {
//                    writeUnAuthMsg(response);
//                    return false;
//                }
//
//                return true;
//            }
//            default:
//                throw new IllegalStateException("Unexpected value: " + authPoicy);
//        }


    }

    /**
     * 在业务处理器处理请求执行完成后，生成视图之前执行(可修改ModelAndView )
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //logger.info("-----------------afterCompletion-- postHandle---------------");
        //preHandle 返回false则不会进入该方法
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //preHandle 返回false则不会进入该方法
//        SessionInfo sessionInfo = SessionUtil.getSession();
//        String key = SessionContext.SESSION_REDIS_KEY_PREFIX + sessionInfo.getSid();
//
//        if (sessionInfo.getClear() == 0) {
//            //redisUtil.del(key);//从redis中删除session数据
//        	//从本地删除session
//            SessionStoreManager.remove(sessionInfo.getSid());
//            return;
//        }
//
//        sessionInfo.setLastTime(DateUtils.getTime());
//        //从本地删除session
//        SessionStoreManager.setSession(key, sessionInfo);
//
//        SessionUtil.clear();
//        sessionInfo = null;
    }


    private void writeErrorMsg(HttpServletResponse response, String code, String msg) throws Exception {
        ResultMsg resultMsg = ResultMsg.fail(code, msg);
        response.getWriter().write(JSON.toJSONString(resultMsg));
    }

    private void writeUnloginMsg(HttpServletResponse response) throws Exception {
        ResultMsg resultMsg = ResultMsg.fail(ResultMsg.UNLOGIN_CODE, "请登录后访问！");
        response.getWriter().write(JSON.toJSONString(resultMsg));
    }

    private void writeUnAuthMsg(HttpServletResponse response) throws Exception {
        ResultMsg resultMsg = ResultMsg.fail(ResultMsg.UNAUTH_CODE, "无权限访问！");
        response.getWriter().write(JSON.toJSONString(resultMsg));
    }

    private boolean authCheck(SessionUser sessionUser, String currentUri, String[] allows) {
        Set<String> auths = sessionUser.getAuths();

        if (auths.contains(currentUri)) {
            return true;
        }

        for (String str : allows) {
            if (auths.contains(str)) {
                return true;
            }
        }

        return false;
    }
}